package com.youshang520i.consuldiscoveryconsumer.controller;

import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.youshang520i.consuldiscoveryconsumer.po.Goods;
import com.youshang520i.consuldiscoveryconsumer.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author youshang
 */
@RestController
public class GoodsController {

    @Autowired
    private GoodsService goodsService;


    @HystrixCommand(fallbackMethod = "fallback",commandProperties = {
            @HystrixProperty(name = "execution.timeout.enabled",value = "true"), //是否给方法执行设置超时，默认为 true。
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1000"), //设置超时时间 默认为10000 (1秒)
            @HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout",value = "true"), //发生超时是是否中断，默认true
            @HystrixProperty(name = "fallback.enabled",value = "true"), //当执行失败或者请求被拒绝，是否会尝试调用hystrixCommand.getFallback() 。默认true
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //一个rolling window内最小的请求数。如果设为20，那么当一个rolling window的时间内（比如说1个rolling window是10秒）收到19个请求，即使19个请求都失败，也不会触发circuit break。默认20
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "5000"), //触发短路的时间值，当该值设为5000时，则当触发circuit break后的5000毫秒内都会拒绝request，也就是5000毫秒后才会关闭circuit。默认5000
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "10") //错误比率阀值，如果错误率>=该值，circuit会被打开，并短路所有请求触发fallback。默认50
    })
    @GetMapping("/goodsList")
    public String goodsList() throws InterruptedException {
        List<Goods> goods = goodsService.selectGoodsList();
        Thread.sleep(1200);
        return JSONObject.toJSONString(goods);
    }

    public String fallback(){
        return "请求超时！！！！";
    }
}
